package com.eight.cloud.message.listener;


import com.eight.cloud.core.utils.format.ObjectFormat;
import com.eight.cloud.message.producer.WebSocketPublisher;
import com.eight.cloud.openfeign.message.model.SocketMessage;
import com.eight.cloud.redisson.utils.RedisListenerActuator;
import com.eight.cloud.redisson.utils.RedisListenerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消息监听
 *
 * @ClassName: RedisListener
 * @Author: TXC
 * @Date: 2024-10-11 09:44
 **/
@Slf4j
@Component
public class RedisListener {
    @Resource
    private RedisListenerUtils listenerUtils;

    @Resource
    private WebSocketPublisher webSocketPublisher;

    public void subscribeToChannel(String channel) {
        RedisListenerActuator listenerActuator = listenerUtils.createActuator(channel);
        listenerActuator.subscribe((ch, message) -> {
            try {
                log.info("Received message on channel {}: {}", ch, message);
                SocketMessage<?> socketMessage = ObjectFormat.objToObject(message, SocketMessage.class);
                webSocketPublisher.send(socketMessage);
                log.info("Message sent successfully to WebSocket");
            } catch (Exception e) {
                // 记录日志，避免程序崩溃
                log.error("Failed to convert message to SocketMessage: {}", message, e);
            }
        });

    }
}
